<?php

	if (!defined('DIR_SEP')) {
	    define('DIR_SEP', DIRECTORY_SEPARATOR);
	}

	if (!defined('MODULES_DIR')) {
	    define('MODULES_DIR', dirname(__FILE__).DIR_SEP."..".DIR_SEP);
	}

	require_once(MODULES_DIR.'ext/magpierss/rss_fetch.inc');
	require_once(MODULES_DIR.'feeds/feed.inc');
	require_once(MODULES_DIR.'feeds/feedItem.inc');
	require_once(MODULES_DIR.'feeds/unifeed.inc');
	require_once(MODULES_DIR.'log.inc');

	$oFeed = new Feed();
	$feeds = $oFeed->allFeeds(false);

	if ($feeds == null || count($feeds) == 0) 
	{
		Log::getInstance()->write('no feeds to process',2);
		return;
	}

	Log::getInstance()->write('Feeds count: '.count($feeds),2);

	foreach($feeds as $feed)
	{
		Log::getInstance()->write("fetching: ".$feed->url,2);

		$rss = false;

		try
		{
			$rss = fetch_rss($feed->url);
		}
		catch(Exception $ex)
		{
			continue;
		}
		if(!$rss)
			continue;

		Log::getInstance()->write('Found '.count($rss->items).' items',2);
		
		Log::getInstance()->write('last post is from '.date('d-m-Y H:i:s',$feed->lastPost).'['.$feed->lastPost.']',2);

		foreach ($rss->items as $item) 
		{
			$unifeed = new Unifeed($item);
				
			$feedTime = $unifeed->getTime();
			
			if(isset($feed->lastPost) && $feed->lastPost >= $feedTime )
				continue;
			
			Log::getInstance()->write('New item from '.date('d-m-Y H:i:s',$feedTime).'['.$feedTime.']',2);
			
			$feedItem = new FeedItem();

			$feedItem->addItem(
				$feed->id,
				$unifeed->getTitle(),
				$unifeed->getLink(),
				$unifeed->getContent(),
				$feedTime );
		}
	}
?>